package com.mlink.ai.chat.ui.activity

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdView
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.ads.*
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.ActivityLanguageBinding
import com.mlink.ai.chat.ui.adapter.LanguageItem
import com.mlink.ai.chat.ui.adapter.LanguageRecyclerAdapter
import com.mlink.ai.chat.utils.AnalyticsEvents
import com.mlink.ai.chat.utils.LanguageUtils
import com.mlink.ai.chat.utils.logEvent
import java.util.*


class LanguageActivity : BaseActivity<ActivityLanguageBinding>() {

    private var nativeAd: NativeAd? = null
    private lateinit var flashAnimator: ObjectAnimator
    private lateinit var languageAdapter: LanguageRecyclerAdapter

    override fun getViewBinding(): ActivityLanguageBinding =
        ActivityLanguageBinding.inflate(layoutInflater)

    override fun initViews() {
        initLanguageRecycler()

        if (AiChatApplication.app.appViewModel.getSubscribeLiveData().value == true) {
            binding.flAd.isVisible = false
        } else {
            nativeAd = adManager.getLanguageNativeAd()
            if (nativeAd == null) {
                initNativeAd()
            } else {
                showNativeAd()
            }
        }

        binding.ivRight.setOnClickListener {
            AnalyticsEvents.AC_LANGUAGE_TICK_CLICK.logEvent()

            languageAdapter.selectedItem?.code?.let {
                if (LanguageUtils.getCurrentLanguageCode() == it) {
                    finish()
                    return@setOnClickListener
                }
                LanguageUtils.changeLanguage(this, it, true)
            }
            val intent = if (intent.getBooleanExtra(KEY_IS_NEED_RELAUNCH, false)) {
                Intent(this, SplashActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                }
            } else {
                Intent(this, MainActivity::class.java)
            }
            startActivity(intent)
            finish()
        }

        AnalyticsEvents.AC_LANGUAGE_PAGE_SHOW.logEvent()
    }

    override fun onDestroy() {
        nativeAd?.destroy()
        nativeAd = null
        adManager.destroyLanguageNativeAd()
        if (::flashAnimator.isInitialized) {
            flashAnimator.cancel()
        }
        super.onDestroy()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initLanguageRecycler() {
        binding.languageRecycler.run {
            layoutManager =
                LinearLayoutManager(this@LanguageActivity, LinearLayoutManager.VERTICAL, false)
            languageAdapter = LanguageRecyclerAdapter()
            adapter = languageAdapter

            post {
                val default =
                    if (LanguageUtils.getCurrentLanguageCode() == null) {
                        Locale.getDefault().language
                    } else {
                        LanguageUtils.getCurrentLanguageCode()
                    }
                when (default) {
                    LanguageItem.ENGLISH_UK.code -> {
                        languageAdapter.selectedItem = LanguageItem.ENGLISH_UK
                    }

                    LanguageItem.BRAZIL.code -> {
                        languageAdapter.selectedItem = LanguageItem.BRAZIL
                    }

                    else -> {
                        languageAdapter.data.forEach {
                            if (default?.startsWith(it.code) == true) {
                                languageAdapter.selectedItem = it
                            }
                        }
                    }
                }
                if (languageAdapter.selectedItem == null) {
                    languageAdapter.selectedItem = LanguageItem.ENGLISH_US
                } else {
                    languageAdapter.data.remove(languageAdapter.selectedItem)
                    languageAdapter.data.add(0, languageAdapter.selectedItem!!)
                }
                languageAdapter.notifyDataSetChanged()
            }
        }


    }

    private fun initNativeAd() {
        val adLoader =
            AdLoader.Builder(AiChatApplication.app, AdMobAdConfig.LANGUAGE_NATIVE_AD.adId)
                .forNativeAd {
                    nativeAd = it
                    nativeAd?.setOnPaidEventListener { adValue ->
                        val adNetwork = nativeAd?.responseInfo?.mediationAdapterClassName ?: "unknown"
                        OxAdValueUtils.logAdmobImpressionRevenue(
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,
                            "native",
                            adNetwork,
                            adValue,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement
                        )
                    }
                    showNativeAd()
                }
                .withAdListener(object : AdListener() {
                    override fun onAdImpression() {
                        super.onAdImpression()
                        val networkName: String? = nativeAd?.responseInfo?.mediationAdapterClassName
                        AdEventUtil.trackAdImpressionEvent(
                            AdFormat.NATIVE,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement,
                            null,
                            networkName,
                            null,
                            0,
                            0,
                            null,
                            0.0
                        )
                    }

                    override fun onAdLoaded() {
                        super.onAdLoaded()
                        val networkName: String? = nativeAd?.responseInfo?.mediationAdapterClassName
                        AdEventUtil.trackAdLoadedEvent(AdFormat.NATIVE,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement,
                            0,null,networkName,null,0,0,null,0.0)
                    }

                    override fun onAdFailedToLoad(p0: LoadAdError) {
                        super.onAdFailedToLoad(p0)
                        AdEventUtil.trackAdLoadFailedEvent(AdFormat.NATIVE,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,
                            AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement,p0.message,0)
                    }

                    override fun onAdClicked() {
                        super.onAdClicked()
                        val networkName: String? = nativeAd?.responseInfo?.mediationAdapterClassName
                        AdEventUtil.trackAdClickEvent(AdFormat.NATIVE, AdMobAdConfig.LANGUAGE_NATIVE_AD.adId, AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement,
                            null,networkName,null, 0,null,0.0)
                    }
                })
                .build()
        AdEventUtil.trackAdRequestEvent(AdFormat.NATIVE, AdMobAdConfig.LANGUAGE_NATIVE_AD.adId, AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement)
        adLoader.loadAd(AdRequest.Builder().build())

        binding.flNativeAdContainer.post(::showAnimation)
    }

    private fun showNativeAd() {
        binding.llLoad.llRoot.isVisible = false
        if (::flashAnimator.isInitialized) {
            flashAnimator.cancel()

        }
        nativeAd?.run {
            val adView = layoutInflater
                .inflate(R.layout.layout_ad_language_native, null) as NativeAdView
            adView.mediaView = adView.findViewById(R.id.ad_image)
            adView.iconView = adView.findViewById(R.id.ad_icon)
            adView.headlineView = adView.findViewById(R.id.ad_headline)
            adView.bodyView = adView.findViewById(R.id.ad_body)
            adView.callToActionView = adView.findViewById(R.id.ad_action)
            adView.adChoicesView = adView.findViewById(R.id.ad_options_view)

            (adView.headlineView as TextView).text = headline
            adView.mediaView?.mediaContent = mediaContent

            adView.iconView?.visibility = if (icon == null) {
                View.INVISIBLE
            } else {
                (adView.iconView as ImageView).setImageDrawable(icon?.drawable)
                View.VISIBLE
            }

            adView.bodyView?.visibility = if (body == null) {
                View.INVISIBLE
            } else {
                (adView.bodyView as TextView).text = body
                View.VISIBLE
            }

            adView.callToActionView?.visibility = if (callToAction == null) {
                View.INVISIBLE
            } else {
                (adView.callToActionView as Button).text = callToAction
                View.VISIBLE
            }
            adView.setNativeAd(this)
            binding.flNativeAdContainer.addView(adView)

            AdEventUtil.trackAdShowEvent(AdFormat.NATIVE, AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement,null)

            val networkName = responseInfo?.mediationAdapterClassName
            AdEventUtil.trackAdShowingEvent(AdFormat.NATIVE, AdMobAdConfig.LANGUAGE_NATIVE_AD.adId,AdMobAdConfig.LANGUAGE_NATIVE_AD.adPlacement, networkName, null)
        }
    }

    private fun showAnimation() {
        val flashIv = findViewById<View>(R.id.iv_flash)
        val flashContainer = findViewById<View>(R.id.ll_root)
        flashAnimator = ObjectAnimator.ofFloat(
            flashIv,
            "translationX",
            0f,
            (flashContainer.width + flashIv.width).toFloat()
        ).also {
            it.duration = 1800
            it.repeatCount = ValueAnimator.INFINITE
            it.repeatMode = ValueAnimator.RESTART
            it.start()
        }
    }

    companion object {
        const val KEY_IS_NEED_RELAUNCH = "key_is_need_relaunch"
    }

}